import React, { Component } from 'react'
import ReactDOM from 'react-dom'

// class Demo extends Component {
//   state = { count: 0 }
//   myRef = React.createRef()
//   add = () => {
//     const { count } = this.state
//     this.setState({ count: count + 1 })
//   }

//   componentDidMount() {
//     setInterval(() => {
//       const { count } = this.state
//       this.setState({ count: count + 1 })
//     }, 1000)
//   }

//   getValue = () => {
//     alert(this.myRef.current.value)
//   }
//   render() {
//     return (
//       <>
//         <h2>当前求和为: {this.state.count}</h2>
//         <button onClick={this.add}>点击</button>
//         <input ref={this.myRef} />
//         <button onClick={this.getValue}>点击获取value</button>
//       </>
//     )
//   }
// }

function Demo() {
    const [count, setCount] = React.useState(0);
    const [obj, setObj] = React.useState({key: '是个对象'});
    
  React.useEffect(() => { //didmount  didupdate
    console.log('@@@')
    let timer = setInterval(() => {
      setCount((count) => count + 1)
    }, 1000)
    return () => {
        clearInterval(timer)
    } ; // 返回的函数相当于willunmount
  }, []) //数组内传入需要监测的数据
  function add() {
    // setCount(count+1)
    console.log(obj);
    setObj({objkey: '修改了key'})
    setCount((count) => count + 1)
  }

  //卸载组件的回调
  function unmount() {
      ReactDOM.unmountComponentAtNode(document.getElementById('root'))
  }

  const myRef = React.useRef();

  function getValue() {
      alert(myRef.current.value)
  }
  return (
    <>
      <h2>当前求和为: {count}</h2>
      <button onClick={add}>点击</button>
      <button onClick={unmount}>点击卸载组件</button>
      <input ref={myRef}/>
      <button onClick={getValue}>点击获取value</button>
    </>
  )
}

export default Demo
